package com.br.aiops.api;

import com.br.aiops.receiver.es.build.Message;
import com.br.aiops.receiver.es.build.MessageBuilder;
import com.br.aiops.receiver.es.config.Config;
import com.br.aiops.receiver.es.config.ConfigCache;
import com.br.aiops.receiver.es.query.DSL;
import com.br.aiops.receiver.es.query.Query;
import com.br.aiops.receiver.es.query.Result;
import com.br.aiops.receiver.es.query.ResultFilter;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * es相关api
 */
@RestController
@RequestMapping("/api/es")
public class ElasticsearchController {

    private Logger LOGGER = LoggerFactory.getLogger(ElasticsearchController.class);

    public static final String COMPUTER_TYPE = "count";

    @Autowired
    private ConfigCache cache;

    @Autowired
    private Query query;

    @GetMapping("/configs")
    public List<Config> configs() {
        return cache.getConfigs();
    }

    @PostMapping("/buildMessage")
    public List<Message> buildMessage(@RequestBody Config config) {
        //从es抓取数据并写出到kafka
        long start = DateUtils.truncate(DateUtils.addMinutes(new Date(), -config.getLastMinutes()), Calendar.MINUTE).getTime();
        long end = DateUtils.truncate(new Date(), Calendar.MINUTE).getTime();

        DSL dsl = DSL.builder()
                .method(config.getMethod())
                .endpoint(config.getEndpoint())
                .body(config.getBody())
                .resultFields(config.getResultFields())
                .build();
        try {
            Result result = query.query(dsl, start, end);
            return buildMessages(config, result);
        } catch (IOException e) {
            LOGGER.error("获取es数据错误。", e);
        }
        return Lists.newArrayList();
    }


    @Nullable
    private List<Message> buildMessages(Config config, Result result) {
        MessageBuilder messageBuilder = MessageBuilder.builder()
                .service(config.getService())
                .errorCode(config.getErrorCode())
                .msg(config.getMessage())
                .hosts(result.getHosts())
                .build();

        //build messages
        switch (config.getResultType()) {
            case Config.RESULT_TYPE_TOTAL:
                return messageBuilder.buildMessage(result.getTotalCount(), result.getMessage());
            case Config.RESULT_TYPE_LIST:
                return messageBuilder.buildMessage(result.getRecords(), result.getMessage());
            case Config.RESULT_TYPE_GROUP:
                ResultFilter filter = result.compute(config.getGroupField());
                //添加了过滤条件
                if (StringUtils.isNotBlank(config.getFilterOperator())) {
                    filter = filter.filter(new ResultFilter.Condition(config.getFilterOperator(), config.getFilterValue()));
                }
                return messageBuilder.buildMessage(filter.getResult(), COMPUTER_TYPE, result.getMessage());
            default:
                return Lists.newArrayList();
        }
    }
}
